
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：后台管理菜单                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-01-04 10:01:02                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： MenuService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.ViewModels.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestTrader.Cms.Services
{
    public class MenuService: IMenuService
    {
        private readonly IMenuRepository _repository;
        private readonly IMapper _mapper;
        private readonly IRolePermissionRepository _roleRepository;

        public MenuService(IMenuRepository repository, IRolePermissionRepository roleRepository, IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
            _roleRepository = roleRepository;
        }

        public IEnumerable<MenuModel> GetMenus(String menuName, String roleStr, String stateStr)
        {
            var filterTitles = new String[] { "帐户资料", "视频认证", "密码修改" };
            var result = new List<MenuModel>();
            int role = 0;
            int state = 0;
            if (int.TryParse(roleStr, out role) && int.TryParse(stateStr, out state))
            {
                var roles = _roleRepository.GetList($"where RoleId={ role }");
                if (roles.Any())
                {
                    var menuIds = string.Join(',', roles.Select(p => p.MenuId));
                    var menus = _repository.GetList($"where Permission=@menuName and Id in({ menuIds }) and IsDisplay=1 and IsDelete=0", new { menuName = menuName });
                    var parentMenus = menus.Where(p => p.ParentId == 0);
                    result = GenerateMenu(parentMenus, menus);
                    // 代理进入且未审核只能查看“视频认证”功能
                    if (role >= 3 && 1 != state)
                    {
                        result.ForEach(item => {
                            item.Items = item.Items.Where(p => filterTitles.Contains(p.Title)).ToList();
                        });
                    }
                }
            }
            return result;
        }

        private List<MenuModel> GenerateMenu(IEnumerable<Menu> parentMenus, IEnumerable<Menu> _menus) {
            var result = new List<MenuModel>();

            foreach (var pMenu in parentMenus)
            {
                var menus = _menus.Where(p => p.ParentId == pMenu.Id);
                var items = new List<MenuItemModel>();
                
                foreach (var menu in menus)
                {
                    items.Add(new MenuItemModel {
                        Title = menu.DisplayName,
                        Href = menu.LinkUrl,
                        Icon = menu.IconUrl,
                        Spread = menu.IsSystem
                    });
                }
                var item = new MenuModel() {
                    MenuIcon = pMenu.IconUrl,
                    MenuName = pMenu.DisplayName,
                    MenuUrl = pMenu.Name,
                    IsPc = pMenu.IsSystem,
                    Items = items
                };

                result.Add(item);
            }

            return result;
        }

        public BaseResult AddOrModify(MenuAddOrModifyModel item)
        {
            var result = new BaseResult();
            Menu model;
            if (item.Id == 0)
            {
                //TODO ADD
                model = _mapper.Map<Menu>(item);
                model.AddManagerId = 1;
                model.IsDelete = false;
                model.AddTime = DateTime.Now;
                if (_repository.Insert(model) > 0)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                //TODO Modify
                model = _repository.Get(item.Id);
                if (model != null)
                {
                    _mapper.Map(item, model);
                    model.ModifyManagerId = 1;
                    model.ModifyTime = DateTime.Now;
                    if (_repository.Update(model) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }


        public BaseResult DeleteIds(int[] Ids)
        {
            var result = new BaseResult();
            if (Ids.Count() == 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonModelStateInvalidMsg;

            }
            else
            {
                var count = _repository.DeleteLogical(Ids);
                if (count > 0)
                {
                    //成功
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    //失败
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }


            }
            return result;
        }

        public TableDataModel LoadData(MenuRequestModel model)
        {
            string conditions = "where IsDelete=0 ";//未删除的
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and DisplayName like '%{model.Key}%'";
            }

            return new TableDataModel
            {
                count = _repository.RecordCount(conditions),
                data = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc").ToList(),
            };
        }

        public BaseResult ChangeDisplayStatus(ChangeStatusModel model)
        {
            var result = new BaseResult();
            //判断状态是否发生变化，没有则修改，有则返回状态已变化无法更改状态的提示
            var isLock = _repository.GetDisplayStatusById(model.Id);
            if (isLock == !model.Status)
            {
                var count = _repository.ChangeDisplayStatusById(model.Id, model.Status);
                if (count > 0)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonDataStatusChangeCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonDataStatusChangeMsg;
            }
            return result;
        }

        /// <summary>
        /// 判断是否存在名为Name的菜单
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        public BooleanResult IsExistsName(MenuAddOrModifyModel item)
        {
            bool data = false;
            if (item.Id > 0)
            {
                data = _repository.IsExistsName(item.Name, item.Id);
            }
            else
            {
                data = _repository.IsExistsName(item.Name);

            }
            var result = new BooleanResult
            {
                Data = data,
            };
            return result;
        }

        public List<Menu> GetChildListByParentId(int ParentId)
        {
            string conditions = "where IsDelete=0 ";//未删除的
            if (ParentId >= 0)
            {
                conditions += " and ParentId =" + ParentId;
            }
            return _repository.GetList(conditions).ToList();

        }
    }
}